/**
 * Software License, Version 1.0
 * 
 * Copyright 2008 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgment:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgment may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or Granules, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called Granules, 
 * nor may Indiana University or Community Grids Lab or Granules appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 * LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 * WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 * NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 * INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 * INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 * "VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 * LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 * ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 * GENERATED USING SOFTWARE.
 */

package cgl.granules.dataset;

import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;

/**
 * This is a class which implements the <code>DataAvailabilityNotifier</code>
 * interface. This class allows implementations of the dataset to use
 * composition to notify the availability or closure of the dataset to the
 * registered observers.
 * 
 * @author Shrideep Pallickara
 * 
 */
public class DatasetNotifier implements DataAvailabilityNotifier {

    private String datasetIdentifier;
    private String datasetBinding;
    private ConcurrentHashMap<String, DataAvailabilityObserver> datasetObservers;
    private ConcurrentHashMap<String, DataAvailabilityObserver> activeObservers;
    private String moduleName = "DatasetNotification: ";
    /*
     * Since there are two data structures that are being used to preserve the
     * invariants, states access/modifications to the 2 objects need to be
     * guarded by this private lock, which cannot be acquired
     */
    private Object notifierLock = new Object();


    public DatasetNotifier(String datasetIdentifier, String datasetBinding) {
        this.datasetIdentifier = datasetIdentifier;
        this.datasetBinding = datasetBinding;
        datasetObservers =
            new ConcurrentHashMap<String, DataAvailabilityObserver>();
        activeObservers =
            new ConcurrentHashMap<String, DataAvailabilityObserver>();
    }


    @Override
    public void pauseAvailabilityNotifications(DataAvailabilityObserver observer)
        throws DatasetException {
        checkForDatasetObserverProblems(observer);
        String observerIdentifier = observer.getIdentifier();
        //synchronized (notifierLock) {
            activeObservers.remove(observerIdentifier);
        //}
    }


    @Override
    public void resumeAvailabilityNotifications(
                                                DataAvailabilityObserver observer)
        throws DatasetException {
        checkForDatasetObserverProblems(observer);
        String observerIdentifier = observer.getIdentifier();
        //synchronized (notifierLock) {
            activeObservers.putIfAbsent(observerIdentifier, observer);
        //}
    }


    /**
     * Called by the dataset as soon as additional data is available.
     * 
     * @param datasetBinding
     */
    public void dataAvailable(String datasetBinding) {
        if (!passBindingCheck(datasetBinding)) {
            System.out.println(moduleName + "Dataset with binding "
                + datasetBinding + "] not authorized to generate availability "
                + "notification on dataset:" + datasetIdentifier);
            return;
        }

        //synchronized (notifierLock) {
            if (activeObservers.isEmpty()) {
                System.out.println(moduleName + "No active observers ... ");
                return;
            }

            Enumeration<DataAvailabilityObserver> e =
                activeObservers.elements();
            while (e.hasMoreElements()) {
                DataAvailabilityObserver observer = e.nextElement();
                observer.onDataAvailability(datasetIdentifier);
            }
            //}
    }


    /**
     * Called by the dataset, just before it is ready to close down.
     * 
     * @param datasetBinding
     */
    public void datasetClosure(String datasetBinding) {
        if (!passBindingCheck(datasetBinding)) {
            System.out.println(moduleName + "Dataset with binding "
                + datasetBinding + "] not authorized to generate availability "
                + "notification on dataset:" + datasetIdentifier);
            return;
        }
        synchronized (notifierLock) {
            if (datasetObservers.isEmpty()) {
                return;
            }

            Enumeration<DataAvailabilityObserver> e =
                datasetObservers.elements();
            while (e.hasMoreElements()) {
                DataAvailabilityObserver observer = e.nextElement();
                observer.onDatasetClosure(datasetIdentifier);
            }
        }
    }


    @Override
    public void deregisterDataAvailabilityObserver(
                                                   DataAvailabilityObserver observer)
        throws DatasetException {
        String errorReport = null;
        checkForDatasetObserverProblems(observer);
        String observerIdentifier = observer.getIdentifier();

        synchronized (notifierLock) {
            DataAvailabilityObserver removedObserver =
                datasetObservers.remove(observerIdentifier);

            if (removedObserver == null) {
                errorReport =
                    moduleName + "Observer with identifier ["
                        + observerIdentifier + "] NOT previously registered.";
                throwDatasetException(errorReport);
            }
            activeObservers.remove(observerIdentifier);
        }
    }


    @Override
    public String getDatasetIdentifier() {
        return datasetIdentifier;
    }


    @Override
    public void registerDataAvailabilityObserver(
                                                 DataAvailabilityObserver observer)
        throws DatasetException {
        String errorReport = null;

        checkForDatasetObserverProblems(observer);
        String observerIdentifier = observer.getIdentifier();
        synchronized (notifierLock) {
            DataAvailabilityObserver previousObserver =
                datasetObservers.putIfAbsent(observerIdentifier, observer);

            if (previousObserver != null) {
                errorReport =
                    moduleName + "Observer with identifier ["
                        + observerIdentifier + "] previously registered.";
                throwDatasetException(errorReport);
            }

            activeObservers.putIfAbsent(observerIdentifier, observer);
        }
    }


    private void checkForDatasetObserverProblems(
                                                 DataAvailabilityObserver observer)
        throws DatasetException {
        String errorReport = null;

        if (observer == null) {
            errorReport = moduleName + "Trying to register a NULL observer";
            throwDatasetException(errorReport);
        } else {
            if (observer.getIdentifier() == null) {
                errorReport =
                    moduleName + "Trying to register an observer"
                        + "with a NULL indentifier";
                throwDatasetException(errorReport);
            }
        }
    }


    /**
     * Does a check to see if the binding that has been passed, matches the one
     * that has been established.
     * 
     * @param binding
     * @return
     */
    private boolean passBindingCheck(String binding) {
        if (binding == null) {
            return false;
        }

        if (binding.equals(datasetBinding)) {
            return true;
        }
        return false;
    }


    private void throwDatasetException(String errorReport)
        throws DatasetException {
        DatasetException dse = new DatasetException(errorReport);
        throw dse;
    }

}
